import express, { Request, Response } from 'express';
import { v4 as uuid } from 'uuid';
import Live from './model/Live';
import Streamer from './model/Streamer';

const router = express.Router();
router.use(express.json());

// 创建新的直播记录
router.post("/lives", async (req, res) => {
  try {
    const { streamerId, startTime, title, path } = req.body;
    const newLive = await Live.create({ 
      id: uuid(), 
      streamerId, 
      startTime, 
      title, 
      path 
    });
    res.status(201).json(newLive);
  } catch (error) {
    res.status(400).json({ error });
  }
});

// 获取所有直播记录
router.get("/lives", async (req, res) => {
  try {
    const lives = await Live.findAll();
    res.json(lives);
  } catch (error) {
    res.status(400).json({ error });
  }
});

// 获取特定主播的直播记录
router.get("/lives/streamer/:streamerId", async (req, res) => {
  try {
    const { streamerId } = req.params;
    const lives = await Live.findAll({
      where: { streamerId }
    });
    res.json(lives);
  } catch (error) {
    res.status(400).json({ error });
  }
});

// 获取单个直播记录
router.get("/lives/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const live = await Live.findOne({
      where: { id }
    });
    
    if (!live) {
      return res.status(404).json({ error: "直播记录未找到" });
    }
    
    res.json(live);
  } catch (error) {
    res.status(400).json({ error });
  }
});

// 更新直播记录
router.put("/lives/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const { streamerId, startTime, duration, title, path } = req.body;
    
    const [affectedCount] = await Live.update(
      {
        streamerId,
        startTime,
        duration,
        title,
        path
      },
      { where: { id } }
    );
    
    if (affectedCount === 0) {
      return res.status(404).json({ error: "直播记录未找到" });
    }
    
    const updatedLive = await Live.findOne({ where: { id } });
    res.json(updatedLive);
  } catch (error) {
    res.status(400).json({ error });
  }
});

// 删除直播记录
router.delete("/lives/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const deletedCount = await Live.destroy({
      where: { id }
    });
    
    if (deletedCount === 0) {
      return res.status(404).json({ error: "直播记录未找到" });
    }
    
    res.sendStatus(200);
  } catch (error) {
    res.status(400).json({ error });
  }
});

// 结束直播并更新时长
router.put("/lives/:id/end", async (req, res) => {
  try {
    const { id } = req.params;
    const { endTime } = req.body;
    
    const live = await Live.findOne({
      where: { id }
    });
    
    if (!live) {
      return res.status(404).json({ error: "直播记录未找到" });
    }
    
    const duration = endTime - live.startTime.getTime();
    
    await Live.update(
      { duration },
      { where: { id } }
    );
    
    res.json({ id, duration });
  } catch (error) {
    res.status(400).json({ error });
  }
});

export default router;